<template>
  <el-card>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input v-model="form.spuName" placeholder="SPU名称"></el-input>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select v-model="form.tmId" placeholder="请选择品牌" width="250px">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in trademarks"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          v-model="form.description"
          placeholder="SPU描述"
          rows="5"
        ></el-input>
      </el-form-item>

      <el-form-item label="SPU图片">
        <el-upload
          action="/admin/product/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleAvatarSuccess"
          :file-list="form.spuImageList || []"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="属性">
        <el-select
          :placeholder="messageAttr"
          width="250px"
          v-model="attrIdAndName"
        >
          <el-option
            :label="attr.name"
            :value="`${attr.id}:${attr.name}`"
            v-for="attr in attrs"
            :key="attr.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndName"
          @click="addAttr"
          >添加销售属性</el-button
        >
      </el-form-item>

      <el-form-item label="属性">
        <el-table
          style="width: 100%"
          border
          size="mini"
          :data="form.spuSaleAttrList"
        >
          <el-table-column type="index" label="序号" width="100px">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名称" width="150px">
          </el-table-column>
          <el-table-column
            prop="spuSaleAttrValueList"
            label="属性标签"
            width="width"
          >
            <template slot-scope="{ row }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(index, row)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="id" label="操作" width="100px">
            <template slot-scope="{ row }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="delAttr(row.baseSaleAttrId)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addOrUpdate">保存</el-button>
        <el-button type="" @click="cancelAttr">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "Spuform",
  data() {
    return {
      form: {
        category3Id: "",
        description: "",
        spuImageList: [],
        spuName: "",
        spuSaleAttrList: [],
        tmId: "",
      },
      resImg: [],
      trademarks: [],
      saleAttrs: [],
      dialogImageUrl: "",
      dialogVisible: false,
      inputVisible: false,
      inputValue: "",
      attrIdAndName: "",
    };
  },
  methods: {
    handleRemove(file, fileList) {
      this.form.spuImageList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file, fileList) {
      this.form.spuImageList.push({
        imgName: file.name,
        imgUrl: res.data,
        spuId: this.form.id,
        uid: file.uid,
      });
    },
    async getTrademarkList() {
      let result = await this.$api.default.spu.getTrademarkList();
      if (result.code == 200) {
        this.trademarks = result.data;
      }
    },
    async getSaleAttr() {
      let result = await this.$api.default.spu.getSaleAttr();
      if (result.code == 200) {
        this.saleAttrs = result.data;
      }
    },

    handleClose(index, row) {
      row.spuSaleAttrValueList.splice(index, 1);
    },

    showInput(row) {
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
      // this.$nextTick((_) => {
      //   this.$refs.saveTagInput.$refs.input.focus();
      // });
    },

    handleInputConfirm(row) {
      if (!row.inputValue.trim()) {
        this.$message({ message: "填写不能为空!", type: "info" });
        return;
      }
      let info = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrName: row.saleAttrName,
        saleAttrValueName: row.inputValue.trim(),
        spuId: row.spuId,
      };
      row.spuSaleAttrValueList.push(info);
      row.inputVisible = false;
    },

    //添加spu属性
    addAttr() {
      let info = this.attrIdAndName.split(":");
      let attr = {
        baseSaleAttrId: info[0],
        saleAttrName: info[1],
        spuId: this.form.id,
        spuSaleAttrValueList: [],
      };
      this.form.spuSaleAttrList.push(attr);
      this.attrIdAndName = "";
    },

    //删除spu属性
    delAttr(id) {
      this.form.spuSaleAttrList = this.form.spuSaleAttrList.filter(
        (item) => item.baseSaleAttrId != id
      );
      this.getSaleAttr();
    },

    //保存功能
    async addOrUpdate() {
      let result = await this.$api.default.spu.addOrUpdateSpu(this.form);
      if (result.code == 200) {
        this.$bus.$emit("setNewStatus", 0);
        this.$message({
          type: "success",
          message: "操作成功!",
        });
      } else {
        this.$message({
          type: "error",
          message: "操作失败!",
        });
      }
    },

    cancelAttr() {
      this.$bus.$emit("setNewStatus", 0);
      this.form = {
        category3Id: "",
        description: "",
        spuImageList: [],
        spuName: "",
        spuSaleAttrList: [],
        tmId: "",
      };
    },
  },
  mounted() {
    this.getTrademarkList();
    this.getSaleAttr();
  },
  computed: {
    attrs() {
      return this.saleAttrs.filter((item) => {
        return !this.form.spuSaleAttrList.some(
          (i) => item.id == i.baseSaleAttrId
        );
      });
    },
    messageAttr() {
      return `还有${this.attrs.length}个未选择`;
    },
  },
};
</script>

<style>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
